import os
import datetime
import subprocess
import yaml
import sys
import logging
import gevent
import psutil as psutil
from gevent import monkey

monkey.patch_all()

from flask import Flask, jsonify, request
from flask_cors import CORS
import utils.logger

app = Flask(__name__)

# app.logger.handlers = []
# 添加CORS中间件，允许所有跨域请求
CORS(app)



@app.route('/', methods=['POST', 'GET'])
def home():
    return 'Hello'


@app.route('/startAnalyze', methods=['POST'])
def start():

    try:
        # 获取请求数据，假设请求的 JSON 数据格式为 {"key": "value"}
        req = request.get_json()
        print(req)
        # 处理请求数据，这里只是简单的返回接收到的数据
        # result = req
        current_script_dir = os.path.dirname(os.path.abspath(__file__))

        with open(os.path.join(current_script_dir, '../conf/yolo.yaml'), 'r') as f:
            data = yaml.load(f, Loader=yaml.FullLoader)

        # 添加字段
        data['uuid'] = req['uuid']

        # 写入YAML文件
        with open(os.path.join(current_script_dir, '../conf/yolo.yaml'), 'w') as f:
            yaml.dump(data, f)

        # 设置当前工作目录为my_project目录
        # os.chdir(current_script_dir)

        # 调用新线程的方式
        # thread = threading.Thread(target=start_yolo, args=(samples,))
        # 启动线程
        # thread.start()
        start_yolo()
        # gevent.spawn(start_yolo, samples)

        # 返回 JSON 响应
        res = {
            'uuid': req['uuid'],
            'result': 0,
            'msg': '',
            'timeDate': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        return jsonify(res), 200
    except Exception as e:
        # 处理异常情况
        res = {
            'uuid': req['uuid'],
            'result': -1,
            'msg': '程序异常',
            'timeDate': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        return jsonify(res), 500


@app.route('/show', methods=['POST'])
def show():
    utils.logger.logger.info("this is show")

    return jsonify({"工作目录": str(os.getcwd())})


@app.route('/stopAnalyze', methods=['POST'])
def stop():
    try:
        # 获取请求数据，假设请求的 JSON 数据格式为 {"key": "value"}
        req = request.get_json()


        p = subprocess.Popen("sudo systemctl stop my_analyze", shell=True)
        res = {
            'uuid': req['uuid'],
            'result': 0,
            'msg': '',
            'timeDate': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        return jsonify(res)
    except Exception as e:
        res = {
            'uuid': req['uuid'],
            'result': -1,
            'msg': '',
            'timeDate': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        return jsonify(res), 500


def start_yolo():
    # yolo.main(streams, None, None, disable_probe)
    current_script_dir = os.path.dirname(os.path.abspath(__file__))
    target_script_path = os.path.join(current_script_dir, "yolo.py")
    # p = subprocess.Popen(
    #     f"python3 {target_script_path} -i {streams[0]} {streams[1]} {streams[2]} --no-display --silent", shell=True,
    #     stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    p = subprocess.Popen("sudo systemctl start my_analyze", shell=True)
    # stdout, stderr = p.communicate()

    # 打印输出结果
    # print("STDOUT:", stdout)
    # print("STDERR:", stderr)


# def terminate_process(pid):
#     try:
#
#         # 这里注意popen获得的pid和系统实际的pid差1，实测
#         process = psutil.Process(pid+1)
#         process.send_signal(psutil.signal.SIGKILL)
#         # logger.info(f"Process {pid} terminated with SIGKILL signal.")
#     except psutil.NoSuchProcess:
# logger.error(f"Process {pid} not found.")


if __name__ == '__main__':
    # app.run(host='0.0.0.0', port=8888, debug=False)
    pass